#include "scorequerybydate.h"
#include "mainwindow.h"
#include "database.h"

ScoreQueryByDate::ScoreQueryByDate(MainWindow *parent)
    : QWidget(parent), mainWindow(parent)
{
    // 获取数据库实例
    database = mainWindow->getDatabase();

    // 初始化日期为今天
    currentDate = QDate::currentDate();

    setupUi();
    refreshData();
}

ScoreQueryByDate::~ScoreQueryByDate()
{
}

void ScoreQueryByDate::setupUi()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 顶部控制区域
    QHBoxLayout *controlLayout = new QHBoxLayout();

    // 日期选择
    QLabel *dateLabel = new QLabel("日期:", this);
    dateEdit = new QDateEdit(currentDate, this);
    dateEdit->setCalendarPopup(true);
    dateEdit->setDisplayFormat("yyyy-MM-dd");

    // 单元选择
    QLabel *unitLabel = new QLabel("单元:", this);
    unitSelect = new QComboBox(this);

    // 查询按钮
    queryButton = new QPushButton("查询", this);
    queryButton->setStyleSheet("background-color: #007bff; color: white; padding: 5px 15px;");

    controlLayout->addWidget(dateLabel);
    controlLayout->addWidget(dateEdit);
    controlLayout->addSpacing(20);
    controlLayout->addWidget(unitLabel);
    controlLayout->addWidget(unitSelect);
    controlLayout->addStretch();
    controlLayout->addWidget(queryButton);

    mainLayout->addLayout(controlLayout);

    // 结果表格
    resultTable = new QTableWidget(this);
    resultTable->setColumnCount(4);
    resultTable->setHorizontalHeaderLabels(QStringList() << "选择" << "房间号" << "评价等级" << "问题");
    resultTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    resultTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    resultTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    resultTable->verticalHeader()->setVisible(false);

    // 表格下方的操作区域
    QHBoxLayout *operationLayout = new QHBoxLayout();

    // 全选复选框
    selectAllCheck = new QCheckBox("全选", this);

    // 删除选中按钮
    deleteSelectedButton = new QPushButton("删除选中", this);
    deleteSelectedButton->setStyleSheet("background-color: #dc3545; color: white; padding: 5px 15px;");

    operationLayout->addWidget(selectAllCheck);
    operationLayout->addStretch();
    operationLayout->addWidget(deleteSelectedButton);

    mainLayout->addWidget(resultTable, 1);
    mainLayout->addLayout(operationLayout);

    // 连接信号和槽
    connect(dateEdit, &QDateEdit::dateChanged, this, &ScoreQueryByDate::onDateChanged);
    connect(unitSelect, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
            this, &ScoreQueryByDate::onUnitChanged);
    connect(queryButton, &QPushButton::clicked, this, &ScoreQueryByDate::onQueryClicked);
    connect(deleteSelectedButton, &QPushButton::clicked, this, &ScoreQueryByDate::onDeleteSelectedClicked);
    connect(selectAllCheck, &QCheckBox::toggled, this, &ScoreQueryByDate::onSelectAllToggled);
}

void ScoreQueryByDate::refreshData()
{
    loadUnits();
    loadData();
}

void ScoreQueryByDate::loadUnits()
{
    // 保存当前选择的单元
    QString currentSelectedUnit = unitSelect->currentText();

    // 清空单元选择
    unitSelect->clear();

    // 加载单元列表
    QStringList units = database->getBuildingUnits();
    unitSelect->addItems(units);

    // 尝试恢复之前选择的单元
    int index = unitSelect->findText(currentSelectedUnit);
    if (index >= 0)
    {
        unitSelect->setCurrentIndex(index);
    }
    else if (!units.isEmpty())
    {
        // 否则选择第一个
        currentUnit = units.first();
    }
}

void ScoreQueryByDate::loadData()
{
    // 清空表格
    resultTable->setRowCount(0);

    // 获取当前日期和单元的评分记录
    QList<Database::ScoreRecord> records;

    if (!currentUnit.isEmpty())
    {
        records = database->getScoresByDateAndUnit(currentDate.toString("yyyy-MM-dd"), currentUnit);
    }
    else
    {
        records = database->getScoresByDate(currentDate.toString("yyyy-MM-dd"));
    }

    if (records.isEmpty())
    {
        return;
    }

    // 填充表格
    resultTable->setRowCount(records.size());

    for (int i = 0; i < records.size(); ++i)
    {
        const Database::ScoreRecord &record = records[i];

        // 创建复选框
        QCheckBox *checkBox = new QCheckBox(this);
        resultTable->setCellWidget(i, 0, checkBox);

        // 设置房间号
        QTableWidgetItem *roomItem = new QTableWidgetItem(record.room);
        roomItem->setData(Qt::UserRole, record.id); // 保存记录ID用于后续删除
        resultTable->setItem(i, 1, roomItem);

        // 设置评级
        QTableWidgetItem *scoreItem = new QTableWidgetItem(record.score);
        resultTable->setItem(i, 2, scoreItem);

        // 设置问题
        QTableWidgetItem *issuesItem = new QTableWidgetItem(record.issues);
        resultTable->setItem(i, 3, issuesItem);

        // 根据评级设置颜色
        QColor rowColor;
        if (record.score == "优")
        {
            rowColor = QColor(200, 255, 200); // 浅绿色
        }
        else if (record.score == "良")
        {
            rowColor = QColor(255, 255, 200); // 浅黄色
        }
        else if (record.score == "差")
        {
            rowColor = QColor(255, 200, 200); // 浅红色
        }

        // 应用颜色到行
        for (int col = 0; col < resultTable->columnCount(); ++col)
        {
            if (col != 0)
            { // 跳过复选框列
                QTableWidgetItem *item = resultTable->item(i, col);
                if (item)
                {
                    item->setBackground(rowColor);
                }
            }
        }
    }

    // 调整列宽
    resultTable->setColumnWidth(0, 50); // 选择列较窄
    resultTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    resultTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    resultTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    resultTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
}

void ScoreQueryByDate::onDateChanged(const QDate &date)
{
    currentDate = date;
    loadData();
}

void ScoreQueryByDate::onUnitChanged(const QString &unit)
{
    currentUnit = unit;
    loadData();
}

void ScoreQueryByDate::onQueryClicked()
{
    loadData();
}

void ScoreQueryByDate::onDeleteSelectedClicked()
{
    QList<int> recordsToDelete;

    // 收集所有选中的记录ID
    for (int row = 0; row < resultTable->rowCount(); ++row)
    {
        QCheckBox *checkBox = qobject_cast<QCheckBox *>(resultTable->cellWidget(row, 0));
        if (checkBox && checkBox->isChecked())
        {
            QTableWidgetItem *item = resultTable->item(row, 1);
            int recordId = item->data(Qt::UserRole).toInt();
            recordsToDelete.append(recordId);
        }
    }

    if (recordsToDelete.isEmpty())
    {
        QMessageBox::information(this, "提示", "请先选择要删除的记录");
        return;
    }

    // 确认是否删除
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除",
                                                              QString("确定要删除选中的 %1 条记录吗？").arg(recordsToDelete.size()),
                                                              QMessageBox::Yes | QMessageBox::No);

    if (reply != QMessageBox::Yes)
    {
        return;
    }

    // 执行删除
    int successCount = 0;
    for (int recordId : recordsToDelete)
    {
        if (database->deleteScoreRecord(recordId))
        {
            successCount++;
        }
    }

    if (successCount > 0)
    {
        QMessageBox::information(this, "删除成功",
                                 QString("成功删除 %1 条记录").arg(successCount));

        // 重新加载数据
        loadData();
    }
    else
    {
        QMessageBox::critical(this, "删除失败", "没有记录被删除");
    }
}

void ScoreQueryByDate::onSelectAllToggled(bool checked)
{
    // 选中或取消选中所有行
    for (int row = 0; row < resultTable->rowCount(); ++row)
    {
        QCheckBox *checkBox = qobject_cast<QCheckBox *>(resultTable->cellWidget(row, 0));
        if (checkBox)
        {
            checkBox->setChecked(checked);
        }
    }
}